<template>
  <!-- 模板部分基本保持不变 -->
  <div class="inner-html-container">
    <div class="page">
      <!-- <div class="grid-space-between" :class="!isMobile ? 'grid-box' : ''"> -->
      <div class="grid-space-between">
        <!-- 左侧会话列表 -->
        <!-- <div class="left-container" :class="{ 'expNo': leftStatus }" v-if="!isMobile"> -->
        <div class="left-container" :class="{ 'expNo': leftStatus }">


          <div class="left-container-title">
            <div class="titleSp">
              <img src="@/assets/images/loge.svg" alt="">
            </div>
            <img @click="setLeft" class="pointer icon1" src="@/assets/images/exp.svg" alt="">

          </div>
          <div v-if="!leftStatus">
            <el-button type="primary"
              style="width: 100%;background: #1C71E6;height: 40px;font-size: 16px;border-radius: 12px;"
              @click="handleAddSession">
              New Chat
              <!-- <span v-if="!leftStatus">新任务</span>
              <span v-else>+</span> -->
            </el-button>
            <div class="hostoryDialogue flex">
              <div>
                <img src="@/assets/images/liao.svg" alt="">

                <span style="padding-left: 4px;">Recent Chat</span>
              </div>
              <div> <img class="pointer" src="@/assets/images/low.svg" alt="">
              </div>
            </div>
            <div class="session-area">
              <div class="dayTime">Today</div>

              <div class="session-item" :class="activeIndex == index ? 'session-item-active' : ''"
                v-for="(item, index) in sessionList" :key="index"
                @click="handleChangeSessionIndex(index, item.dialogId)">
                <span :class="activeIndex == index ? 'active-node' : 'normal-node'" v-if="editIndex != index">{{
                  item.query ?? item.title }}</span>
                <el-input :ref="`renameRef_${index}`" autofocus v-model="item.title" v-else size="small"
                  style="width: 120px" @blur="editIndex = -1" @change="editIndex = -1" />
                <div class="icon-box">
                  <!--<el-icon class="icon" color="#E6A23C" @click.stop="handleFocusInput(index)">
                    <Brush />
                  </el-icon>-->
                  <el-icon class="icon" color="#91959A" @click.stop="handleDeleteSession(index, item)">
                    <Delete />
                  </el-icon>
                </div>
              </div>
            </div>

          </div>
          <div v-else>

            <div class="sentere leftMune"> <img src="@/assets/images/lanliao.svg" alt=""></div>
            <div class="sentere pointer leftMune">
              <!-- hover -->
              <el-popover popper-class="inDig" :offset="12" :show-arrow="false" placement="right-start" trigger="click">
                <template #reference>
                  <img src="@/assets/images/huiliao.svg" alt="">
                </template>
                <template #default>
                  <div class="openDig">
                    <div class="title">
                      全部对话
                    </div>
                    <el-scrollbar max-height="200px">

                      <div class="constent">
                        <div class="dayTime">
                          Today
                        </div>
                        <div class="session-item pointer" :class="activeIndex == index ? 'session-item-active' : ''"
                          v-for="(item, index) in sessionList" :key="index"
                          @click="handleChangeSessionIndex(index, item.dialogId)">
                          <span :class="activeIndex == index ? 'active-node' : 'normal-node'"
                            v-if="editIndex != index">{{
                              item.query ?? item.title }}</span>
                          <el-input :ref="`renameRef_${index}`" autofocus v-model="item.title" v-else size="small"
                            style="width: 120px" @blur="editIndex = -1" @change="editIndex = -1" />
                          <el-icon class="icon" color="#91959A" @click.stop="handleDeleteSession(index, item)">
                            <Delete />
                          </el-icon>
                        </div>
                      </div>
                    </el-scrollbar>
                  </div>
                </template>
              </el-popover>
              <!-- <img src="@/assets/images/huiliao.svg" alt=""> -->
            </div>
          </div>
          <div class="flex userLow">
            <div class="sentere" style="padding-bottom: 0;"> <img src="@/assets/images/userF.svg" alt=""></div>
            <span v-if="!leftStatus">User_test</span>
          </div>
        </div>

        <!-- 主聊天区域 -->
        <div class="container">
          <div class="message-master">
            <div class="images-preview" v-if="imgPreviewUrl">
              <div class="header">
                <el-icon :size="16" @click="hideImagePreview">
                  <Close />
                </el-icon>
              </div>
              <div class="img-container">
                <el-image :src="imgPreviewUrl" fit="contain"
                  style="max-width: 100%; max-height: 100%;overflow: auto;" />
              </div>
            </div>

            <el-scrollbar ref="scrollBarRef" v-if="queryInfos.messages.length > 0" @scroll="handleResize">
              <div class="message-area">
                <!-- {{ queryInfos.value?.messages ?? [] }} -->
                <MessageComp ref="messageRef" :message="queryInfos.messages"></MessageComp>
              </div>
            </el-scrollbar>

            <div class="holle-area">
              <div class="hi" v-if="!queryInfos.messages.length > 0">
                <span>

                  Hi，I am 021
                </span>
              </div>
              <!-- {{isMobile}} -->
              <!-- <div class="input-area" :class="isMobile ? 'left-space' : ''"> -->
              <div class="input-area ">
                <div v-if="showDownBtn && queryInfos.messages.length > 0" class="down-btn-wrapper"
                  @click="scrollToBottom">
                  <el-icon :size="72">
                    <DownBtn />
                  </el-icon>
                </div>
                <div v-if="currentFile">
                  <!-- {{currentFile}} -->
                  <fileShow :fileName="currentFile.name" :fileType="currentFile.type" :showCloseButton="true"
                    @close="clearFile"></fileShow>
                </div>
                <div>

                  <el-input @focus="handleInputAreaFocus" @click="handleInputAreaFocus" class="iiin" :style="{
                    '--el-input-border-color': 'transparent',
                    '--el-input-hover-border-color': 'transparent',
                    '--el-input-focus-border-color': 'transparent'
                  }" type="textarea" resize="none" :rows="3" v-model="queryKeys" id="keyInput"
                    placeholder="What do you want to research?" />
                </div>
                <div class="inputBtu">
                  <div class="flex">
                    <!-- trigger="hover" -->
                    <el-popover popper-class="inSetbtu" :offset="4" :show-arrow="false" placement="bottom-start"
                      trigger="click">
                      <template #reference>
                        <el-button class="setThis">
                          <img :src="btu.btu" alt="">
                          {{ btu.text }}
                        </el-button>
                      </template>
                      <template #default>
                        <div class="ind" v-for="value in btuAll">
                          <el-button v-if="value.disable" round class="no-border setThis">
                            <el-icon v-if="value.text = '产测问题智能分析模型'" class="btn-icon">
                              <TestModelIcon />

                            </el-icon>
                            <img v-else :src="value.btu" alt="">
                            {{ value.text }}
                          </el-button>
                          <el-button v-else round class="no-border setThis" @click="setMoren(value)">
                            <img :src="value.btu" alt="">
                            {{ value.text }}
                          </el-button>
                        </div>
                      </template>
                    </el-popover>

                    <el-upload ref="uploadRef" class="upload-demo ml-12" :limit="1" :on-exceed="handleExceed"
                      :show-file-list="false" :auto-upload="false" accept=".pdf" :on-change="handleFileChange">
                      <template #trigger>
                        <el-button class="inThisCircle" circle>
                          <img src="@/assets/images/daochu.svg" alt="">
                        </el-button>
                      </template>
                    </el-upload>

                  </div>
                  <el-button class="custom-padding" type="primary" @click="handleRequest"
                    :disabled="!queryKeys && !currentFile" :loading="loading">
                    <el-icon :size="16">
                      <Top />
                    </el-icon>

                  </el-button>
                </div>

              </div>
              <div class="footlow">All content generated by AI, please discern carefully.© Copyright 2025, All Rights
                Reserved by
                Zhejiang lab | 浙ICP备18016057号-15</div>
              <div class="moren" v-if="!queryInfos.messages.length > 0">
                <div class="moren-item pointer" v-for="(value, index) in moren" @click="AutoQuest(value.text)">
                  <img :src="value.btu" alt="">
                  <span>{{ value.text, index }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="message-Att" v-show="rightStatus">

            <rightShow @close="closeRight"></rightShow>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import OpenAI from "openai";
import MessageComp from "./components/messageComp.vue";
import { Promotion, Delete, Brush, Top, Close } from "@element-plus/icons-vue";
import { getTokens } from "@/api/modules/deepseek.js";
import { ElMessage, ElMessageBox } from "element-plus";
import MobileDetect from "mobile-detect";
import { emitter } from '@/utils/emitter.js'

import DownBtn from "./components/DownBtn/DownBtn.vue"


import fileShow from '@/components/fileShowcard.vue'

import rightShow from './rightShow.vue'
import { imageResolve, startQuery, generateRendering, dialogList, taskList, deleteDialog } from '@/api/modules/demo.js'

import { convertToStructuredArray, processApiResponse, convertDigMages, sendData } from './useSetMages'
import { useImagePreview } from './useImagePreview';
import TestModelIcon from '../deepseek/components/TestModelIcon/TestModelIcon.vue'
import { size } from 'lodash-es';
import { useTemplateRef } from 'vue';

const router = useRouter();
const route = useRoute();
const scrollBarRef = useTemplateRef("scrollBarRef")

const queryDialogId = route.query.dialogId;

// 响应式数据
// const isMobile = ref(false);
const sessionList = ref([]);
const activeIndex = ref(-1);
const editIndex = ref(-1);
const totalAmt = ref(0);
const queryKeys = ref("");
const loading = ref(false);
const messageRef = ref(null);
const renameRefs = ref({});

const { imgPreviewUrl, hideImagePreview } = useImagePreview()

// 左侧状态
const storageLeftStatus = localStorage.getItem('leftStatus') === 'true' ? true : false;
const leftStatus = ref(storageLeftStatus);
const changeLeftWidth = () => {
  if (leftStatus.value) {
    document.documentElement.style.setProperty('--left-menu-width', '60px');
  } else {
    document.documentElement.style.setProperty('--left-menu-width', '300px');
  }
}
changeLeftWidth();

const queryInfos = ref({
  dialogId: null,
  messages: [],
  model: "deepseek-chat",
  stream: true,
});
const rightStatus = ref(false)
const closeRight = () => {
  rightStatus.value = false
}
emitter.on('setRightStatus', (data) => {
  console.log("data", data);

  rightStatus.value = data
})

const btu = ref({
  btu: new URL('@/assets/images/btu1.svg', import.meta.url).href,
  text: '通用大模型'
})


const moren = [{

  btu: new URL('@/assets/images/line4.svg', import.meta.url).href,
  text: '请提取图纸中型号NCA9617-DMSR的器件参数，生成原理图符号和封装文件'
}, {
  btu: new URL('@/assets/images/line0.svg', import.meta.url).href,
  text: '请提取LSF0204DPWR型号参数，生成相应的封装库文件'
}, {

  btu: new URL('@/assets/images/line1.svg', import.meta.url).href,
  text: '74LVC07AS14-13型号的封装文件请帮我生成'
}, {

  btu: new URL('@/assets/images/line3.svg', import.meta.url).href,
  text: '提取MC74HC4052ADTR2G型号封装和原理图符号'
}]

const btuAll = [{
  btu: new URL('@/assets/images/btu1.svg', import.meta.url).href,
  text: '通用大模型',
  disable: false,
}, {
  btu: new URL('@/assets/images/btu2.svg', import.meta.url).href,
  text: '器件参数智能提取模型',
  disable: false,
}, {
  btu: new URL('@/assets/images/btu3.svg', import.meta.url).href,
  text: '产测问题智能分析模型',
  disable: true
}]

const setMoren = (val) => {
  btu.value = val
}

const AutoQuest = (val) => {
  queryKeys.value = val
  handleRequest()
}

const clearFile = () => {

  uploadRef.value.clearFiles()
  currentFile.value = null
  console.log("pe", currentFile);


}

const apiKey = import.meta.env.VITE_DEEPSEEK_API_KEY;
const openai = ref(null);


const setLeft = () => {
  leftStatus.value = !leftStatus.value;
  localStorage.setItem('leftStatus', leftStatus.value);
  changeLeftWidth();
}

const uploadRef = ref(null)
const currentFile = ref(null)

const handleExceed = (files) => {
  uploadRef.value.clearFiles()
  const file = files[0]
  uploadRef.value.handleStart(file)
}

const handleFileChange = (file) => {
  currentFile.value = file
  currentFile.value.type = file.name.split('.').pop().toLowerCase()
  console.log('当前文件:', file)
}
// 判断当前是否有文件
const hasFile = () => {
  return currentFile.value !== null
}

const initIndex = () => {
  const queryDialogIndex = getDialogIndex(queryDialogId);
  activeIndex.value = queryDialogIndex > -1 ? queryDialogIndex : -1;
  if (activeIndex.value != -1) {
    handleChangeSessionIndex(activeIndex.value, queryDialogId);
    queryInfos.value.messages = sessionList.value[activeIndex.value]?.messages || [];
    queryInfos.value.dialogId = queryDialogId;
  }
};

// 初始化方法
const initSessionList = async () => {
  return await dialogList().then(res => {
    sessionList.value = res.data;
    return res;
  })
    .finally(() => {
      initIndex();
    })
  // sessionList.value = JSON.parse(localStorage.getItem("list") || "[]");
};


// const initOpenAI = () => {
//   openai.value = new OpenAI({
//     baseURL: "https://api.deepseek.com",
//     apiKey: apiKey,
//     dangerouslyAllowBrowser: true,
//   });
// };

// const initToken = async () => {
//   const res = await getTokens({
//     deepseek: "Y",
//     gptToken: apiKey,
//   });
//   const { balance_infos = [] } = res;
//   balance_infos.forEach((o) => {
//     totalAmt.value += Number(o.total_balance);
//   });
// };

// 核心功能方法
const handleClearStorage = () => {
  // localStorage.removeItem("list");
  // localStorage.removeItem("index");
  queryInfos.value.messages = [];
  sessionList.value = [];
  activeIndex.value = -1;
};



const routeSwichSessionIDSave = (dialogId) => {
  if (dialogId) {
    router.push({ name: 'deepseek', query: { dialogId } });
  } else {
    router.push({ name: 'deepseek' });
  }
}

const getDialogIndex = (dialogId) => {
  // 根据返回对话列表找到当前的对话索引
  const cureentSeesionIndex = sessionList.value.findIndex((session) => {
    return session.dialogId === dialogId;
  });

  // 将当前对话索引赋值给当前活动索引
  if (cureentSeesionIndex >= 0) {
    activeIndex.value = cureentSeesionIndex;
  } else {
    activeIndex.value = -1;
    if (queryDialogId) {
      ElMessage({ type: "warning", message: `无法加载${dialogId}` });
      routeSwichSessionIDSave();
    }
  }
  return cureentSeesionIndex;
}



const handleAddSession = () => {
  hideImagePreview()
  if (loading.value) {
    ElMessage({ type: "warning", message: "请当前问题查询完成后重试！" });
    return;
  }
  emitter.emit('setRightStatus', false)

  // sessionList.value.push({
  //   title: `对话${sessionList.value.length + 1}`,
  //   crtTime: new Date(),
  //   messages: [],
  // });

  queryInfos.value.messages = [];

  // 添加对话时，取消选中状态
  activeIndex.value = -1;

  routeSwichSessionIDSave();
};

const handleDeleteSession = (index = 0, val) => {
  ElMessageBox.confirm("确认删除当前对话？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    console.log("e492", val);
    await deleteDialog({ dialogId: val.dialogId })

    await dialogList().then(res => {
      sessionList.value = res.data;
    });

    // initSessionList();
    // sessionList.value.splice(index, 1);

    if (index == activeIndex.value) {
      activeIndex.value = -1;
      handleChangeSessionIndex(activeIndex.value);

    }
    // else if (index < activeIndex.value) {
    //   activeIndex.value--;
    // }

    // queryInfos.value.messages = ;
  }).catch(() => { });
};

const handleFocusInput = (index) => {
  editIndex.value = index;
  nextTick(() => {
    renameRefs.value[`renameRef_${index}`].focus();
  });
};

const handleChangeSessionIndex = async (index, dialogId) => {
  hideImagePreview()

  if (loading.value) {
    ElMessage({ type: "warning", message: "请当前问题查询完成后重试！" });
    return;
  }
  emitter.emit('setRightStatus', false)

  const res = await taskList({ dialogId: dialogId })
  routeSwichSessionIDSave(dialogId);
  console.log("e391", convertDigMages(res.data));

  activeIndex.value = index;
  queryInfos.value.messages = sessionList.value[activeIndex.value]?.messages || [...convertDigMages(res.data)];
  queryInfos.value.dialogId = sessionList.value[activeIndex.value]?.dialogId || null
  forceScrollToBottom();
};

const forceScrollToBottom = () => {
  // messageRef.value?.scrollBottom(true);
};
function convertUploadFileToFile(uploadRawFile) {
  if (!uploadRawFile || !(uploadRawFile instanceof Blob)) {
    console.warn('Invalid upload file raw data');
    return null;
  }

  try {
    // 从原始数据创建标准File对象
    return new File([uploadRawFile], uploadRawFile.name || 'unnamed_file', {
      type: uploadRawFile.type || 'application/octet-stream',
      lastModified: uploadRawFile.lastModified || Date.now()
    });
  } catch (error) {
    console.error('File conversion failed:', error);
    return null;
  }
}
const handleRequest = async () => {
  console.log('currentFile.value', currentFile.value);

  if (!queryKeys.value && !currentFile.value) return;
  if (!sessionList.value.length) {
    await handleAddSession();
  }
  console.log("E33");

  if ((queryInfos.value?.messages?.length ?? 0) > 0 &&
    queryInfos.value.messages[queryInfos.value.messages.length - 1].type == 'btu' &&
    queryInfos.value.messages[queryInfos.value.messages.length - 1].filetype == "none") {

    if (queryInfos.value.messages[queryInfos.value.messages.length - 2].type == 'btu') {
      queryInfos.value.messages.pop()
      queryInfos.value.messages.pop()
      queryInfos.value.messages.pop()
    } else {
      // queryInfos.value.messages.pop()
      // queryInfos.value.messages.pop()
    }
  }


  if (currentFile?.value?.raw ?? null) {
    let a = URL.createObjectURL(convertUploadFileToFile(currentFile?.value?.raw))
    queryInfos.value.messages.push({
      role: "user", filename: currentFile?.value?.name, type: 'pdf', state: 1,
      tabname: currentFile?.value?.name, filetype: "pdf", pdfUrl: a
    });

    console.log("e573", {
      role: "user", filename: currentFile?.value?.name, type: 'pdf', state: 1,
      tabname: currentFile?.value?.name, filetype: "pdf", pdfUrl: convertUploadFileToFile(currentFile?.value?.raw)
    });

  }

  console.log("e67");

  if (queryKeys.value) {
    queryInfos.value.messages.push({
      role: "user",
      content: queryKeys.value,
      type: 'text'
    });
  }

  let pra = { query: queryKeys.value, file: currentFile?.value?.raw ?? null }
  // return
  queryKeys.value = "";
  clearFile()
  // forceScrollToBottom();



  try {
    loading.value = true;
    console.log("415");

    queryInfos.value.messages.push({ role: "assistant", content: "已接受任务，开始处理...", type: 'text' });

    // messageRef.value.isAutoScroll = true;

    if (route.query.dialogId) {
      pra.dialogId = route.query.dialogId
    }

    // 解析文档，定位图片
    const response = await startQuery(pra);

    // 重新获取对话列表
    await dialogList().then(res => {
      sessionList.value = res.data;
    });

    const newDialogIndex = getDialogIndex(response.data.dialogId);

    if (newDialogIndex !== -1) {
      routeSwichSessionIDSave(response.data.dialogId);
    }
    console.log("yy", newDialogIndex)

    queryInfos.value.dialogId = response.data.dialogId;
    queryInfos.value.messages.push(...convertToStructuredArray(response.data, (pra?.file ?? null)));

    console.log("e426", queryInfos);

    // 解析图片
    const res = await imageResolve({ taskId: response.data.taskId })
    queryInfos.value.messages[queryInfos.value.messages.length - 1].data = processApiResponse({
      ...res.data,
      symbolImage: response.data.symbolImage, packageImage: response.data.packageImage
    })
    queryInfos.value.messages[queryInfos.value.messages.length - 1].state = 1

    sendData(queryInfos.value.messages[queryInfos.value.messages.length - 1])
    // arr3.pop();
    // arr3.push('newLast');
    // console.log("e430",responseJson);

    queryInfos.value.messages.push(processApiResponse({
      ...res.data,
      symbolImage: response.data.symbolImage, packageImage: response.data.packageImage
    }))
    queryInfos.value.messages.push({ role: "assistant", content: "你还可以进行以下操作：", type: 'text' });

    console.log("queryInfos", res);
    console.log("queryInfos", res.data.componentId + '型号效果图');

    // 效果图生成
    queryInfos.value.messages.push({ taskId: res.data.taskId, dialogId: res.data.taskId, type: "btu", componentId: res.data.componentId, tabname: res.data.componentId + '型号效果图', filetype: "img2", displayTexts: ['效果图生成中...', '效果图生成完成', '生成效果图'], state: 2 })
    queryInfos.value.messages.push({ taskId: res.data.taskId, dialogId: res.data.taskId, type: "btu", componentId: res.data.componentId, filetype: "none", displayTexts: ['封装库生成中...', '封装库生成完成', '生成封装库'], state: 2 })

    // const res2 = await generateRendering({ taskId: response.data.taskId })
    // queryInfos.value.messages[queryInfos.value.messages.length - 1].data = res2.data

    // console.log("334e", res2.data);

    // queryInfos.value.messages.push({ ...res2.data, type: 'img2' })


    // for await (const part of response) {
    //   queryInfos.value.messages[queryInfos.value.messages.length - 1].content += part.choices[0]?.delta?.content || "";
    //   messageRef.value?.scrollBottom();
    // }

    // messageRef.value?.scrollBottom();
    // sessionList.value[activeIndex.value].messages = queryInfos.value.messages;
  } catch (error) {
    console.log("ee", error);
    // ElMessage.error("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
    emitter.emit('setRightStatus', false)

    queryInfos.value.messages.push({
      role: "assistant",
      content: "解析失败,请稍后重试!",
      type: 'text'
    });
    console.log("ee", queryInfos.value);

  } finally {
    loading.value = false;
  }
};


emitter.on('setRendering', (data) => {
  console.log("data99", data);

  handleRequest1(data)

})
const handleRequest1 = async (data) => {
  try {
    loading.value = true;

    queryInfos.value.messages.pop()
    queryInfos.value.messages.pop()
    queryInfos.value.messages.pop()

    queryInfos.value.messages.push({ taskId: data.taskId, dialogId: data.dialogId, type: "btu", componentId: data.componentId, tabname: data.componentId + '型号效果图', filetype: "img2", displayTexts: ['效果图生成中...', '效果图生成完成', '生成效果图'], state: 0 })

    sendData(queryInfos.value.messages[queryInfos.value.messages.length - 1])

    // 效果图生成
    const res2 = await generateRendering({ taskId: data.taskId })
    queryInfos.value.messages[queryInfos.value.messages.length - 1].data = res2.data
    queryInfos.value.messages[queryInfos.value.messages.length - 1].state = 1
    sendData(queryInfos.value.messages[queryInfos.value.messages.length - 1])

    console.log("334e", res2.data);

    queryInfos.value.messages.push({ ...res2.data, type: 'img2' })

    // queryInfos.value.messages.push({ role: "assistant", content: "你还可以进行以下操作：", type: 'text' });
    queryInfos.value.messages.push({ taskId: res2.data.taskId, dialogId: res2.data.taskId, type: "btu", componentId: data.componentId, filetype: "none", displayTexts: ['封装库生成中...', '封装库生成完成', '生成封装库'], state: 2 })

  } catch (error) {
    console.log("ee", error);

    queryInfos.value.messages.push({
      role: "assistant",
      content: "解析失败,请稍后重试!",
      type: 'text'
    });
    console.log("ee", queryInfos.value);
    emitter.emit('setRightStatus', false)

  } finally {
    loading.value = false;
  }

}

// 生命周期
onMounted(() => {


  // // 设备检测
  // const md = new MobileDetect(window.navigator.userAgent);
  // isMobile.value = !!md.mobile();

  // 回车事件监听
  const keyInput = document.getElementById("keyInput");
  if (keyInput) {
    keyInput.addEventListener("keydown", (event) => {
      if (event.key === "Enter") {
        handleRequest();
        event.preventDefault();
      }
    });
  }

  forceScrollToBottom();
});

// 初始化
initSessionList();

// initOpenAI();
// initToken();

// 监听器
watch([sessionList, activeIndex], () => {
  const list = sessionList.value.map((o, i) => {
    if (i == activeIndex.value) {
      return {
        ...o,
        messages: queryInfos.value.messages,
      };
    }
    return { ...o };
  });

  // localStorage.setItem("list", JSON.stringify(list));
  // localStorage.setItem("index", JSON.stringify(activeIndex.value));
}, { deep: true });

const curScrollHeight = ref(0)
const curClientHeight = ref(0)
const curDis = ref(0);
const maxDis = ref(0);
const initScrollData = () => {
  setTimeout(() => {
    const wrap = scrollBarRef.value.wrapRef;
    const scrollHeight = wrap.scrollHeight;
    const clientHeight = wrap.clientHeight;

    const dis = scrollHeight - clientHeight;
    maxDis.value = dis;
    scrollToBottom();
  }, 1000)
}
watch(() => queryInfos, () => {
  initScrollData();
}, {
  immediate: true,
  deep: true
})
const showDownBtn = computed(() => {
  const target = curDis.value < maxDis.value;
  // return target
  return false
})
const handleResize = ({ scrollTop }) => {
  curDis.value = scrollTop
}
const scrollToBottom = () => {


  setTimeout(() => {

    scrollBarRef.value.scrollTo({
      top: maxDis.value
    })
  }, 0)
}
const handleInputAreaFocus = () => {
  console.log('focus')
  scrollToBottom();
}
</script>

<style scoped lang="scss">
:root {
  --left-menu-width: 300px;
}

.flex {
  display: flex;
  justify-content: space-between;
}

.ml-12 {
  margin-left: 12px;
}

.userLow {
  position: absolute;
  left: 0;
  // right: 0;
  bottom: 0;
  justify-self: start;
  align-items: center;
  padding: 16px;
  // background: rgb(216.8, 235.6, 255);
  // .sentere{
  //   padding-bottom: 0 !important;
  // }

  span {
    padding-left: 16px;
  }
}


.pointer {
  cursor: pointer;
}

.no-border {
  border: none !important;
  color: var(--el-button-text-color) !important;

  .btn-icon {
    margin-right: 6px;
    color: #333;
  }
}

.inner-html-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgb(216.8, 235.6, 255);
  // min-width: 1400px;

  .page {
    width: 100%;
    height: 100%;
    background: #fff;
    box-shadow: 0 0 12px 12px rgb(197.7, 225.9, 255);
    box-sizing: border-box;
    // border-radius: 8px;
    overflow: hidden;

    .grid-space-between {
      height: 100%;
      // width: 300px;
      display: flex;


      .left-container {
        background-color: #F0F4F8;
        padding: 0px 16px;
        height: 100%;
        width: 300px;
        box-sizing: border-box;
        transition: width 0.3s ease;
        flex-shrink: 0;
        position: relative;
        z-index: 10;

        &.expNo {
          width: 60px;

          .icon1 {
            transform: rotate(180deg);
          }

          .titleSp {
            display: none;
          }

          .left-container-title {
            justify-content: center;
          }

          .sentere {
            display: flex;
            justify-content: center;
            padding-bottom: 16px;

            &.leftMune {
              padding: 2px 0;
              border-radius: 8px;
              margin-bottom: 10px;

              &:hover {
                background: #DCE6F7;
              }
            }
          }
        }

        .left-container-title {
          display: flex;
          justify-content: space-between;
          padding: 22px 0px;
          align-items: center;

          .titleSp {
            font-size: 20px;
            font-weight: 600;
            color: #333333;
            height: 20px;

            img {

              height: 100%;
            }
          }
        }

        .hostoryDialogue {
          // display: ;
          font-size: 16px;
          color: #333333;
          align-items: center;
          padding: 20px 0;

          &>div {
            display: flex;
            align-items: center;
          }
        }

        .session-area {
          width: 100%;
          height: calc(90vh - 32px - 24px - 12px - 32px);
          // margin-top: 12px;
          box-sizing: border-box;
          overflow-y: auto;

          .dayTime {
            font-size: 14px;
            font-weight: normal;
            line-height: 20px;
            color: #A4A8AD;
            padding-bottom: 14px;
          }

          .session-item {
            height: 36px;
            line-height: 36px;
            margin-bottom: 8px;
            border-radius: 4px;
            padding: 0 18px;
            // background: rgb(199.5, 201, 204);
            color: #666666;
            font-size: 16px;
            display: flex;

            justify-content: space-between;
            align-items: center;
            cursor: pointer;


            span {
              width: 210px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .normal-node {
              // padding-left: 14px;
            }

            .icon-box {
              // visibility: visible;
              visibility: hidden;
              display: grid;
              // column-gap: 8px;
              // grid-template-columns: repeat(2, 1fr);

              .icon {
                cursor: pointer;
              }
            }

            &:hover .icon-box {
              visibility: visible;
            }
          }

          .session-item-active {
            border-radius: 12px;
            opacity: 1;
            color: #333333;
            background: #FFFFFF;
            font-size: 16px;
            box-shadow: 0px 2px 4px 0px rgba(11, 45, 92, 0.05);

            span {
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .active-node {
              // display: flex;
              // align-items: center;

              &::before {
                // display: inline-block;
                // content: "";
                // width: 6px;
                // height: 6px;
                // background: #fff;
                // border-radius: 50%;
                // margin-right: 8px;
              }
            }
          }
        }
      }

      .container {
        width: calc(100vw - var(--left-menu-width));
        height: 100%;
        background: #fff;
        position: relative;
        display: flex;
        justify-content: center;
        flex: 1;


        .message-master {
          width: 50%;
          // max-width: 48rem;
          flex: 1;
          height: 100vh;
          display: flex;
          flex-direction: column;
          position: relative;

          .images-preview {
            position: absolute;

            // max-width: 48rem;
            // margin-inline: auto;
            width: 100%;
            height: calc(100% - 32px);
            margin: 16px 0;
            box-sizing: border-box;
            padding: 0 16px 24px 16px;
            // min-width: 800px;
            z-index: 2;
            display: flex;
            flex-direction: column;
            border-radius: 16px;
            border: 1px solid #EBEBEB;
            background-color: #fff;

            // left: 0;
            // right: 0;
            // margin: auto;
            .header {
              height: 48px;
              background-color: #fff;
              display: flex;
              justify-content: flex-end;
              align-items: center;

              .el-icon {
                width: 24px;
                height: 24px;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
              }
            }

            .img-container {
              // flex: 1;
              // width: calc(100% - 40px);
              width: calc(100% - 40px);
              height: 100%;
              background-color: #333333;
              display: flex;
              justify-content: center;
              align-items: center;
              padding: 10px;
              overflow: auto;
              margin: auto;
            }
          }

          .holle-area {
            width: 100%;
            max-width: 50rem;
            margin: auto;
            padding: 0 16px;
            padding-bottom: 40px;
            box-sizing: border-box;

            .hi {
              padding-top: 10vh;
              padding-bottom: 64px;

              span {
                font-size: 32px;
                font-weight: bold;
                line-height: 48px;

                color: #333333;
              }

              text-align: center;
            }


            .moren {
              display: flex;
              flex-wrap: wrap;
              justify-content: center;
              padding-top: 16px;

              .moren-item {

                // width: 300px;
                height: 40px;
                border-radius: 21px;
                background: #FFFFFF;
                box-sizing: border-box;
                border: 1px solid #EBEBEB;
                font-size: 14px;
                color: #333333;
                margin: 8px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding-right: 10px;
                padding-left: 5px;

                img {
                  margin: 0 10px;
                }

                span {
                  // width: 250px;
                  // overflow: hidden;
                  // /* 超出部分隐藏 */
                  // white-space: nowrap;
                  // /* 禁止换行 */
                  // text-overflow: ellipsis;
                  // /* 显示省略号 */
                  // padding-right: 6px;
                }
              }
            }
          }

          .footlow {
            font-size: 12px;
            color: #979797;
            line-height: 40px;
            text-align: center;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 40px;
          }
        }

        .message-area {
          height: 100%;
          flex: 1;
          padding: 16px 16px 0 16px;
          // overflow: auto;
        }

        .user-tokens {
          height: 30px;
          line-height: 30px;
          padding: 0 8px 0 0;
          font-size: 14px;
          color: #c7c8ca;
          user-select: none;
        }

        .left-space {
          margin-left: 16px;
        }

        .input-area {
          z-index: 1;
          position: relative;

          :deep(.el-button--primary) {
            background-color: #1c71e6;
          }

          box-sizing: border-box;
          // overflow: hidden;
          background: #fff;
          // padding: 0 16px 16px 0;
          border-radius: 16px;

          border: 1px solid #EBEBEB;
          box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.05);
          padding: 12px;
          position: relative;

          .down-btn-wrapper {
            cursor: pointer;
            z-index: 9999;
            position: absolute;
            top: -72px;
            left: 50%;
            transform: translateX(-50%);
          }

          .inputBtu {
            display: flex;
            justify-content: space-between;
          }

        }

        .ind {
          padding: 4px 0;


        }


      }
    }

  }
}

.message-Att {
  flex: 1;
  width: 50%;
}
</style>
<style lang="scss">
.inSetbtu {
  padding: 8px 4px !important;
  border-radius: 16px !important;
  background: #FFFFFF;
  box-sizing: border-box;
  border: 1px solid #EBEBEB !important;
  box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  width: auto !important;
}

.inDig {
  padding: 12px 14px;
  border-radius: 12px !important;
  background: #FFFFFF;
  box-shadow: 0px 6px 14px 0px rgba(0, 0, 0, 0.1);
  width: auto !important;

  .title {
    font-size: 16px;
    font-weight: 600;
    line-height: 24px;
    color: #3D3D3D;
    padding: 14px 8px;
  }

  .dayTime {
    font-size: 14px;
    font-weight: normal;
    line-height: 22px;
    color: #A4A8AD;
    padding: 6px 8px;
  }

  .el-scrollbar {
    width: 300px;
  }

  .session-item {

    font-size: 16px;
    font-weight: normal;
    line-height: 24px;
    color: #666666;
    padding: 6px 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    /* white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis; */
    /* background-color: red; */
    span {
      /* background-color: red; */
      display: inline-block;
      width: 250px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .icon {
      visibility: hidden;

    }

    &:hover {
      .icon {

        visibility: visible;
      }
    }

    &.session-item-active {
      border-radius: 12px;
      /* opacity: 1; */
      color: #333333;
      background: #EEF4FD;
      /* font-size: 16px; */


      // span {
      //   white-space: nowrap;
      //   overflow: hidden;
      //   text-overflow: ellipsis;
      // }

      // .active-node {
      //   display: flex;
      //   align-items: center;

      //   // &::before {
      //   //   display: inline-block;
      //   //   content: "";
      //   //   width: 6px;
      //   //   height: 6px;
      //   //   background: #fff;
      //   //   border-radius: 50%;
      //   //   margin-right: 8px;
      //   // }
      // }
    }
  }
}

.el-textarea.iiin {
  .el-textarea__inner {
    padding: 0;
    font-size: 16px;
    font-weight: normal;
    line-height: 24px;
    color: #333333;
  }
}

.setThis.el-button {
  border-radius: 8px;

  img {
    margin-right: 6px;
  }
}

.inThisCircle.el-button {
  border-radius: 8px;

}

.setThis.el-button:not(.is-disabled):hover {
  color: var(--el-button-text-color) !important;

}

.custom-padding {
  padding: 8px 8px !important;
  /* 上下8px 左右16px */
}
</style>
